package com.blades.monitor;

import com.blades.item.CountMonitorItem;
import com.blades.item.CountTimeMonitorItem;

import java.util.Map;

/**
 * Created by shuangjun.yang on 2016/3/17.
 * 业务监控操作
 */
public class BusinessMonitor extends BaseMonitor {

    private static BusinessMonitor ourInstance = new BusinessMonitor();

    public static BusinessMonitor getInstance() {
        return ourInstance;
    }

    private BusinessMonitor() {
    }
    public void recordCount(String name, long count) {
        CountMonitorItem countMonitorItem =  countItemMap.get(name);
        if(countMonitorItem == null){
            countMonitorItem = new CountMonitorItem();
            CountMonitorItem originalItem =  countItemMap.putIfAbsent(name, countMonitorItem);
            if(originalItem != null){
                countMonitorItem = originalItem;
            }
        }
        countMonitorItem.addCount(count);
    }

    public void recordCountTime(String name, long count, double time) {
        CountTimeMonitorItem countTimeMonitorItem =  countTimeItemMap.get(name);
        if(countTimeMonitorItem == null){
            countTimeMonitorItem = new CountTimeMonitorItem();
            CountTimeMonitorItem originalItem =  countTimeItemMap.putIfAbsent(name, countTimeMonitorItem);
            if(originalItem != null){
                countTimeMonitorItem = originalItem;
            }
        }
        countTimeMonitorItem.addCountAndTime(count,time);
    }

    public void getBusinessMonitorDataMap(Map<String,Number> map){
        for(Map.Entry<String,CountMonitorItem> entry : countItemMap.entrySet()){
            String countKey = entry.getKey()+COUNT_SUFFIX;
            map.put(countKey,entry.getValue().getAndClear());
        }
        for(Map.Entry<String,CountTimeMonitorItem> entry : countTimeItemMap.entrySet()){
            String countKey = entry.getKey()+COUNT_SUFFIX;
            String timeKey = entry.getKey()+TIME_SUFFIX;
            CountTimeMonitorItem countTimeMonitorItem = entry.getValue().getAndClear();
            map.put(countKey,countTimeMonitorItem.getCountSize());
            map.put(timeKey,countTimeMonitorItem.getTime());
        }
    }
}
